package org.jwcloud.project.config;

import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.*;

@SpringBootConfiguration
@EnableAsync
public class AsyncConfig implements AsyncConfigurer {
    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor threadPool = new ThreadPoolTaskExecutor();
        //设置核心线程数
        threadPool.setCorePoolSize(6);
        //设置最大线程数
        threadPool.setMaxPoolSize(12);
        //线程池所使用的缓冲队列
        threadPool.setQueueCapacity(50);
        //等待任务在关机时完成--表明等待所有线程执行完
        //threadPool.setWaitForTasksToCompleteOnShutdown(true);
        // 等待时间 （默认为0，此时立即停止），并没等待xx秒后强制停止
        //threadPool.setAwaitTerminationSeconds(60);
//        threadPool.setKeepAliveSeconds(20);
        BlockingQueue<Runnable> queue = new ArrayBlockingQueue<Runnable>(25);
        RejectedExecutionHandler handler = new RejectedExecutionHandler() {
            @Override
            public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                if (!executor.isShutdown()){
                    try {
                        executor.getQueue().put(r);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        threadPool.setRejectedExecutionHandler(handler);
        //  线程名称前缀
        threadPool.setThreadNamePrefix("Derry-Async-");
        threadPool.initialize();
        return threadPool;
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return null;
    }
}
